package resources.util;

import java.sql.Connection;
import java.sql.SQLException;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class MySqlConnect {
	
	private static Connection connection;
	public static Connection getConnection() {
		return connection;
	}
	
	public static void connect(){
		try {
            Context initContext  = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            dataSource = (DataSource)envContext.lookup("jdbc/hvsolution"); 
        } catch (NamingException e) {
            e.printStackTrace();
        }	
	}

	public static void setConnection(Connection connection) {
		MySqlConnect.connection = connection;
	}

	private static DataSource dataSource;
	
	public static void open() {
		try {
			if(dataSource==null){
				connect();
			}
			connection=dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close() {
		try {
			if(connection!=null){
				connection.close();
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}
}
